package com.example.smartcity_poverty.ui.AllService.Attorneys.activity

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity_poverty.App
import com.example.smartcity_poverty.App.Companion.getToken
import com.example.smartcity_poverty.Base.BaseRecyclerAdapter
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.model.Attreneys.AttListModel
import com.example.smartcity_poverty.logic.model.Attreneys.AttLvShiListAllModel
import com.example.smartcity_poverty.logic.model.Attreneys.AttMoreModel
import com.example.smartcity_poverty.logic.util.Util
import com.example.smartcity_poverty.logic.util.Util.show
import kotlinx.android.synthetic.main.activity_att_show_list_all.*
import kotlinx.android.synthetic.main.re_att_home_list_all.*
import kotlinx.android.synthetic.main.re_att_more.*
import kotlinx.coroutines.Dispatchers

/**
 * 分页获取律师列表
 */
class AttShowListAllActivity : AppCompatActivity() {


    // 根据id来查找律师列表信息
    var lvShiId = 0

    var lvShiSortBy = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_att_show_list_all)
        title = "律师列表"

        // 根据id查找相关律师列表哦
        val id = intent.getStringExtra("id")
        id?.let {
            lvShiId = id.toInt()
        }

        // 下拉菜单适配器
        ArrayAdapter.createFromResource(
            this,
            R.array.spinner_array,
            android.R.layout.simple_list_item_1
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            spinner.adapter = adapter
        }

        // 点击事件选中状态
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(p0: AdapterView<*>?) {

            }

            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                if (p2 == 0) {
                    lvShiSortBy = 0
                    coroutine(Dispatchers.Main){
                        setAttListAll(lvShiId, lvShiSortBy)
                    }
                }
                if (p2 == 1) {
                    lvShiSortBy = 1
                    coroutine(Dispatchers.Main){
                        setAttListAll(lvShiId, lvShiSortBy)
                    }
                }
                if (p2 == 2) {
                    lvShiSortBy = 2
                    coroutine(Dispatchers.Main){
                        setAttListAll(lvShiId, lvShiSortBy)
                    }
                }
                if (p2 == 3) {
                    lvShiSortBy = 3
                    coroutine(Dispatchers.Main){
                        setAttListAll(lvShiId, lvShiSortBy)
                    }
                }
            }

        }

        var t = false
        attAll.setOnClickListener {
            runOnUiThread {
                if (!t) {
                    attOneRvLayout.visibility = View.VISIBLE
                    t = true
                } else {
                    attOneRvLayout.visibility = View.GONE
                    t = false
                }
            }
        }

        coroutine(Dispatchers.IO) {
            setOverride()
            setAttListAll(lvShiId, lvShiSortBy)
        }


    }

    /**
     * 筛选功能实现
     */
    private suspend fun setOverride() {
        // 发起网络请求获取数据
        api.getAttMoreAll(getToken()).apply {
            if (this.code == 200) {
                runOnUiThread {
                    this.rows?.let { it ->
                        attHomeMore.apply {
                            this.layoutManager = GridLayoutManager(context, 2).apply {
                                this.orientation = GridLayoutManager.HORIZONTAL
                            }
                            this.adapter =
                                AttMoreAllAdapter(ArrayList<AttMoreModel.RowsBean>().apply {
                                    this.addAll(it)
                                }, R.layout.re_att_more)
                        }
                    }

                }
            } else runOnUiThread { this.msg?.show() }
        }
    }


    /**
     * 展示律师列表
     */
    private val arrayList = ArrayList<AttLvShiListAllModel.RowsBean>()
    private lateinit var adapter: AttListAllAdapter

    private suspend fun setAttListAll(id: Int, lvShiSortBy: Int) {
        if (id == 0){
            // 获取数据
            api.getAttLvShiListAll(getToken(), null).apply {
                if (this.code == 200) {
                    // 清空数据
                    arrayList.clear()
                    // 填充数据
                    arrayList.addAll(this.rows!!)



                    // RecyclerView适配器
                    runOnUiThread {
                        attHomeListRv.apply {
                            this.isNestedScrollingEnabled = false
                            this.layoutManager = LinearLayoutManager(context)
                        }
                        adapter = AttListAllAdapter(lvShiSortBy, arrayList, R.layout.re_att_home_list_all)
                        attHomeListRv.adapter = adapter
                        adapter.notifyItemChanged(arrayList.size)
                    }

                } else runOnUiThread { this.msg?.show() }
            }
        }else {
            // 获取数据
            api.getAttLvShiListAll(getToken(), id).apply {
                if (this.code == 200) {
                    // 清空数据
                    arrayList.clear()
                    // 填充数据
                    arrayList.addAll(this.rows!!)

                    // RecyclerView适配器
                    runOnUiThread {
                        attHomeListRv.apply {
                            this.isNestedScrollingEnabled = false
                            this.layoutManager = LinearLayoutManager(context)
                        }
                        adapter = AttListAllAdapter(lvShiSortBy, arrayList, R.layout.re_att_home_list_all)
                        attHomeListRv.adapter = adapter
                        adapter.notifyItemChanged(arrayList.size)
                    }

                } else runOnUiThread { this.msg?.show() }
            }
        }


    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }

    /**
     * 律师列表适配器
     */
    inner class AttListAllAdapter(
        private val lvShiSortBy: Int,
        val list: MutableList<AttLvShiListAllModel.RowsBean>,
        layoutId: Int
    ) : BaseRecyclerAdapter<AttLvShiListAllModel.RowsBean>(list, layoutId) {
        override fun setData(
            view: BaseViewHolder.ViewFind,
            data: AttLvShiListAllModel.RowsBean,
            position: Int,
            holder: BaseViewHolder
        ) {

            if (lvShiSortBy == 0) {}
            if (lvShiSortBy == 1) { list.sortBy { it -> it.workStartAt } }
            if (lvShiSortBy == 2) { list.sortByDescending { it -> it.serviceTimes } }
            if (lvShiSortBy == 3) { list.sortByDescending { it -> it.favorableCount } }

            // 填充数据
            val d = list[position]
            val fv = holder.viewFind
            val con = holder.viewFind.view?.context


            Util.glide(App.url + d.avatarUrl, fv.attListUserImage)
            fv.attListUserName.text = d.name
            fv.attListUserTime.text = "工作起始时间: ${d.workStartAt}"
            fv.attListUserSize.text = "咨询人数: ${d.serviceTimes}人"
            fv.attListUserYes.text = "法律专长: ${d.legalExpertiseName}"
            fv.attListUserAll.text = "好评率: ${d.favorableCount}%"

            fv.attListUserBtnOk.setOnClickListener {
                con?.startActivity(Intent(con, AttorneysShowActivity::class.java).apply {
                    putExtra("id", d.id.toString())
                })
            }

        }
    }


    /**
     * 法律专长列表适配器
     */
    inner class AttMoreAllAdapter(
        val list: MutableList<AttMoreModel.RowsBean>,
        layoutId: Int
    ) : BaseRecyclerAdapter<AttMoreModel.RowsBean>(list, layoutId) {
        override fun setData(
            view: BaseViewHolder.ViewFind,
            data: AttMoreModel.RowsBean,
            position: Int,
            holder: BaseViewHolder
        ) {
            // 排序
            list.sortByDescending { it.id }

            // 填充数据
            val d = list[position]
            val fv = holder.viewFind
            // val con = holder.viewFind.view?.context

            Util.glide(App.url + d.imgUrl, fv.attMoreImage)
            fv.attMoreTitle.text = d.name

            holder.itemView.setOnClickListener {
                attAll.text = d.name
                lvShiId = d.id
                coroutine(Dispatchers.Main){
                    coroutine(Dispatchers.Main){
                        setAttListAll(d.id, lvShiSortBy)
                    }
                }
                attOneRvLayout.visibility = View.GONE
            }
        }
    }
}